<?php

class Upload
{
    private $ext;

    private $file;
    private $savaFile;
    private $allowExt;

    private $fileSavaPath;

    private $error = [
        UPLOAD_ERR_INI_SIZE => '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值',
        UPLOAD_ERR_FORM_SIZE => '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。',
        UPLOAD_ERR_PARTIAL => '文件只有部分被上传。',
        UPLOAD_ERR_NO_FILE => '没有文件被上传。',
        UPLOAD_ERR_NO_TMP_DIR => '找不到临时文件夹。',
        UPLOAD_ERR_CANT_WRITE => '文件写入失败。'
    ];

    /**
     * @param string $ext
     */
    public function setExt(string $ext)
    {
        $this->ext = $ext;
    }

    /**
     * @param mixed $savaFile
     */
    public function setSavaFile($savaFile)
    {
        $this->savaFile = $savaFile;
    }

    public function __construct($filedName, $savaName, $allowExt = ['zip', 'xlsx', 'xls'])
    {
        $this->file = $_FILES[$filedName];
        $this->ext = pathinfo($this->file['name'])['extension'] ?? "";
        $this->savaFile = $savaName;
        $this->allowExt = $allowExt;
    }

    /**
     * 检查上传错误
     * @return bool|mixed
     */
    private function _checkError()
    {
        if ($this->file['error'] != UPLOAD_ERR_OK) {
            return $this->error[$this->file['error']];
        }
        return false;
    }

    /**
     * 检查上传错误
     * @return bool
     */
    private function _checkExt()
    {
        return in_array($this->ext, $this->allowExt);
    }


    public function upload()
    {
        //上传错误
        $error = $this->_checkError();
        if ($error !== false) {
            return $error;
        }

        if (!$this->_checkExt()) {
            return "文件类型不符!";
        }

        if (!file_exists($this->savaFile)) {
            mkdir($this->savaFile, 0777, true);
        }

        $fileSavaPath = $this->savaFile . substr(md5(uniqid()), 8, 8) . "." . $this->getExt();;
        $this->fileSavaPath = $fileSavaPath;
        if (file_exists($fileSavaPath)) {
            unlink($fileSavaPath);
        }
        $isSavaBoolen = move_uploaded_file($this->file["tmp_name"], $fileSavaPath);
        return $isSavaBoolen ? "" : "保存文件失败！";

    }

    /**
     * @return mixed
     */
    public function getFileSavaPath()
    {
        return $this->fileSavaPath;
    }

    /**
     * @return string
     */
    public function getExt(): string
    {
        return $this->ext;
    }

    /**
     * @return mixed
     */
    public function getSavaFile()
    {
        return $this->savaFile;
    }
}